package com.nt.train.controller;

import com.nt.train.dto.DemoDto;
import com.nt.train.dto.ValidVO;
import com.nt.train.dto.ValidationDto;
import com.nt.train.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Email;

/**
 * https://www.cnblogs.com/pandaNHF/p/15711253.html
 * 集成hibernate-validator
 * @author hlf
 * @version 1.0
 * @date 2022/9/26 14:37
 */
@RestController
@Slf4j
@Validated
@RequestMapping(value ="/valid")
public class ValidController {


    /**
     * https://www.jb51.net/article/248947.htm
     * RequestBody校验
     * @param validVO
     * @return
     */
    @PostMapping("/valid/test1")
    public String test1(@Validated @RequestBody ValidVO validVO){
        log.info("validEntity is {}", validVO);
        return "test1 valid success";
    }

    /**
     *Form校验
     * @param validVO
     * @return
     */
    @PostMapping(value = "/valid/test2")
    public String test2(@Validated ValidVO validVO){
        log.info("validEntity is {}", validVO);
        return "test2 valid success";
    }

    /**
     *单参数校验
     * @param email
     * @return
     */
    @GetMapping(value = "/valid/test3")
    public String test3(@Email String email){
  //  public String test3(@Email @RequestParam("email") String email){
        log.info("email is {}", email);
        return "email valid success";
    }

    /**
     *单参数校验
     * @param email
     * @return
     */
    @PostMapping(value = "/valid/test4")
    public String test4(@Email String email){
        log.info("email is {}", email);
        return "email valid success";
    }


    /**
     * https://www.cnblogs.com/pandaNHF/p/15711253.html
     * @param validationTestVo
     * @return
     */
    @PostMapping(value ="/test1")
    @ResponseBody
    public ValidationDto testValidation(@Validated @RequestBody ValidationDto validationTestVo){
        return validationTestVo;
    }

    /**
     * https://www.cnblogs.com/exmyth/p/15560926.html
     * @param demo
     * @param result
     * @return
     */
    @PostMapping("/test2")
    public ResultVo demo2(@RequestBody @Valid DemoDto demo, BindingResult result){
        StringBuilder  stringBuilder  = new StringBuilder();
        if(result.hasErrors()){
            for (ObjectError error : result.getAllErrors()) {
                System.out.println(error.getDefaultMessage());
                stringBuilder.append(error.getDefaultMessage()).append("/");
            }
        }
        return ResultVo.ok(stringBuilder.toString());
    }
}
